package com.elite.groovy.callback

import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.time.LocalDate
/**
 * @use 录音自动抽检
 * @author Rick 2024 01-29
 */

public class AutoKHNAssign_Record implements ServiceBackInvoke  {
    private static final Log log = LogFactory.getLog(AutoKHNAssign_Record.class);
    private String charset = "utf-8"; //设置字符集
    private int timeout = 100000; //设置请求超时时间
    private int enableSSLflag = 0;

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response){

        log.debug("----------------------------------录音质检自动抽检分配启动----------------------------------");
        List KHNAssignList = eliteBean.chaxun_sql("Select CHECKGUID,Staffid, Rolegroupid, Summarytmplidlist, Businesstype1, Businesstype2, Businesstype3, Timetype, Callstarttime, Callendtime, Workstarttime, Workendtime, Ratio, Khby, Type, Config_Id From Khn_Spot_Check Where Strattime <= To_Char(Sysdate, 'yyyy-mm-dd') And Endtime >= To_Char(Sysdate, 'yyyy-mm-dd') and Type='luyin' ", "dataSource");

        if (KHNAssignList.size() > 0) {
           // ReCordKHNAssign_ADD(eliteBean, KHNAssignList); //加抽
            ReCordKHNAssign(eliteBean, KHNAssignList); //常规抽
        }
    }

    /**
     * @use 录音加抽
     * 确保坐席在当月时间内，抽取数量/存在录音天数 至少大于等于1，如果小于1,则需要补抽这个坐席录音
     */
    private static ReCordKHNAssign_ADD(EliteBean eliteBean, List KHNAssignList) {

        //定义加抽Log
        String RECORDKHNLOG = "";
        for (def i = 0; i < KHNAssignList.size(); i++) {
            log.debug("执行抽检规则：" + KHNAssignList[i].get("CHECKGUID"));
            String Checkguid = KHNAssignList[i].get("CHECKGUID"); //抽检规则guid
            String Rolegroupid = KHNAssignList[i].get("Rolegroupid"); //抽取组
            String Staffid = KHNAssignList[i].get("Staffid"); //抽取人
            String Summarytmplidlist = KHNAssignList[i].get("Summarytmplidlist"); //小结模板
            String Businesstype1 = KHNAssignList[i].get("Businesstype1"); //小结业务类型1
            String Businesstype2 = KHNAssignList[i].get("Businesstype2"); //小结业务类型2
            String Businesstype3 = KHNAssignList[i].get("Businesstype3"); //小结业务类型3
            String Timetype = KHNAssignList[i].get("Timetype"); //时间段
            String Callstarttime = KHNAssignList[i].get("Callstarttime"); //通话时长开始
            String Callendtime = KHNAssignList[i].get("Callendtime"); //通话时长结束
            String Workstarttime = KHNAssignList[i].get("Workstarttime"); //入职开始时间
            String Workendtime = KHNAssignList[i].get("Workendtime"); //入职结束时间
            String Ratio = KHNAssignList[i].get("Ratio"); //抽取比例
            String Khby = KHNAssignList[i].get("Khby"); //质检员
            String Config_Id = KHNAssignList[i].get("Config_Id"); //质检计划
            String AutomaticGUID = UUID.randomUUID().toString(); //当前抽检批次GUID

            //质检计划、抽检比例、质检员不为空，执行方法
            if (!Config_Id.equals("") && !Ratio.equals("") && !Khby.equals("")) {

                String WhereCondition = ""; //SQL条件片段
                if (!KHUtil.isNull(Staffid)) { //抽取坐席
                    WhereCondition += " and r.staff_id in (" + Staffid + ") ";
                }
                if (!KHUtil.isNull(Rolegroupid)) { //抽取业务组
                    WhereCondition += " and st.title in (" + Rolegroupid + ") ";
                }
                if (!KHUtil.isNull(Summarytmplidlist)) { //小结模板
                    WhereCondition += " and ec.SUMMARYTMPLID in (" + Summarytmplidlist + ") ";
                }
                if (!KHUtil.isNull(Businesstype1)) { //业务1级
                    WhereCondition += " and ec.CALLNATUREGROUP_id in (" + Businesstype1 + ") ";
                }
                if (!KHUtil.isNull(Businesstype2)) { //业务2级
                    WhereCondition += " and ec.callnature_id in (" + Businesstype2 + ") ";
                }
                if (!KHUtil.isNull(Businesstype3)) { //业务3级
                    WhereCondition += " and ec.callnature3_id in (" + Businesstype3 + ") ";
                }
                if (!KHUtil.isNull(Timetype)) { //时间段
                    WhereCondition += " and dt.dateitem_id in (" + Timetype + ") ";
                }
                if (!KHUtil.isNull(Callstarttime)) { //通话时长开始时间段
                    WhereCondition += " and (r.endtime - r.starttime)*24*60*60 >= '" + Callstarttime + "' ";
                }
                if (!KHUtil.isNull(Callendtime)) { //通话时长时间段
                    WhereCondition += " and (r.endtime - r.starttime)*24*60*60 <= '" + Callendtime + "' ";
                }
                if (!KHUtil.isNull(Workstarttime)) { //入职开始时间
                    WhereCondition += " and trunc(months_between(sysdate,to_date(to_char(employeddate,'yyyymm'),'yyyymm')))> '" + Workstarttime + "' ";
                }
                if (!KHUtil.isNull(Workendtime)) { //入职结束时间
                    WhereCondition += " and trunc(months_between(sysdate,to_date(to_char(employeddate,'yyyymm'),'yyyymm')))< '" + Workendtime + "' ";
                }

                //获取当月1号,加抽不跨月
                LocalDate firstDayOfMonth = LocalDate.now().withDayOfMonth(1);  //获取当前日期并设置为1号
                WhereCondition += " and r.starttime >= to_date('" + firstDayOfMonth + "','yyyy-MM-DD HH24:mi:ss')";
                //log.debug("【WhereCondition】：" + WhereCondition);
                //取当月电话数据
                String AssignCountSQL = '''select r.staff_id,
                                                    sum(case when ka.ASSIGNLIST_GUID is null then 1 else 0 end) as notkhncount, -- 未被质检
                                                    sum(case when ka.ASSIGNLIST_GUID is not null then 1 else 0 end) as iskhncount, -- 已被质检
                                                    count(DISTINCT to_char(STARTTIME,'yyyy-mm-dd')) as call_days -- 电话天数
                                                    from record r 
                                                      left join KHN_ASSIGNLIST ka on r.RECORD_GUID=KA.RELATIONID1  
                                                      left join rolegroup rg on r.rolegroup_id=rg.rolegroup_id  
                                                      left join eventcallnature ec on ec.event_guid = r.event_guid
                                                      left join staff st on r.staff_id=st.staff_ID
                                                      left join WMSK_STATISFACTION wss on wss.event_guid=r.event_guid   
                                                    where 1=1  
                                                    and st.Exemption = 0  
                                                    and nvl(wss.STATISFACTION1,0) >= 0  
                                                    and nvl(wss.STATISFACTION1,0) <= 2
                                                ''' + WhereCondition + " group by r.staff_id";

                log.debug("各坐席质检数据SQL:" + AssignCountSQL);
                List AssignCountList = eliteBean.chaxun_sql(AssignCountSQL, "dataSource");
                //拼接数据日志
                RECORDKHNLOG = RECORDKHNLOG + "当前加抽基础数据情况：" + AssignCountList.toString()
                log.debug("加抽日志输出：" + RECORDKHNLOG);
                //每次更换规则时，初始化质检员取序
                int j = 0;
                if (AssignCountList.size() > 0) {
                    int iskhncount, call_days, notkhncount, addkhncount = 0
                    String addstaff_id = '';
                    for (int t = 0; t < AssignCountList.size(); t++) {
                        String ADDWhereCondition = ''; //初始化加抽SQL条件
                        iskhncount = AssignCountList[t].get("iskhncount"); //已被质检数
                        call_days = AssignCountList[t].get("call_days"); //电话天数
                        notkhncount = AssignCountList[t].get("notkhncount"); // 未被质检
                        addstaff_id = AssignCountList[t].get("staff_id"); // 加抽坐席
                        //已被质检小于电话天数，则未达到每日一通的数量，需补全
                        if (iskhncount < call_days && notkhncount > 0) {
                            addkhncount = call_days - iskhncount;

                            //检查加抽数量是否大于未被质检数，则此次未被质检数作为加抽数
                            if (addkhncount > notkhncount) {
                                addkhncount = notkhncount
                            }

                            //拼接加抽SQL
                            ADDWhereCondition += " and r.staff_id='" + addstaff_id + "'";
                            ADDWhereCondition += " and rownum<=" + addkhncount + "";
                            //增加抽检排序，确保每次抽取数据是最新的
                            ADDWhereCondition += " order by r.STARTTIME desc ";
                            //查询坐席可被加抽分配数据
                            String ADDAssignCountSQL = '''select distinct record_guid,r.rolegroup_id,r.staff_id
                                                    from record r 
                                                      left join KHN_ASSIGNLIST ka on r.RECORD_GUID=KA.RELATIONID1  
                                                      left join rolegroup rg on r.rolegroup_id=rg.rolegroup_id  
                                                      left join eventcallnature ec on ec.event_guid = r.event_guid
                                                      left join staff st on r.staff_id=st.staff_ID
                                                      left join WMSK_STATISFACTION wss on wss.event_guid=r.event_guid   
                                                    where 1=1 
                                                    and ka.assignlist_guid is null 
                                                    and nvl(wss.STATISFACTION1,0) >= 0  
                                                    and nvl(wss.STATISFACTION1,0) <= 2
                                                    and st.Exemption = 0  
                                                ''' + WhereCondition + ADDWhereCondition;
                            List ADDAssignCountList = eliteBean.chaxun_sql(ADDAssignCountSQL, "dataSource");

                            //拼接数据日志
                            RECORDKHNLOG = RECORDKHNLOG + "-----当前坐席" + addstaff_id + "可被加抽分配数据：" + ADDAssignCountList.size();
                            //处理质检员为List，并打乱List数据
                            String KhbyArrString = Khby.replace("\"", "");
                            String[] KhbyArr = KhbyArrString.split(",");



                            for (int k = 0; k < ADDAssignCountList.size(); k++) {
                                //数据写入准备
                                String ADDASSIGNLIST_GUID = UUID.randomUUID().toString();
                                String ADDrecord_guid = ADDAssignCountList[k].get("record_guid"); //取需分配录音ID
                                String ADDstaff_id = ADDAssignCountList[k].get("staff_id"); //取录音坐席
                                //需循环到第几位质检员
                                String KhbyID = KhbyArr[j];
                                String DEFAULTROLEGROUP = "";
                                List DEFAULTROLEGROUPLIST = eliteBean.chaxun_sql("select DEFAULTROLEGROUP from staff where STAFF_ID=" + KhbyID + "", "dataSource");
                                if (DEFAULTROLEGROUPLIST.size() > 0) {
                                    DEFAULTROLEGROUP = DEFAULTROLEGROUPLIST.get(0).get("DEFAULTROLEGROUP");
                                }
                                //写入加抽数据
                                String[] data = new String[2];
                                data[0] = "insert into KHN_ASSIGNLIST(Automatic_guid,ASSIGNLIST_GUID,KHTYPE,KHCONFIG_ID,KHCONFIGDATE_ID,BUILDDATE,RECORDBY,KHFLAG,RELATIONID1,KHTOBY,KHGROUP,KHBY,CHECKGUID)values('" + AutomaticGUID + "','" + ADDASSIGNLIST_GUID + "','0','" + Config_Id + "','B2126F83-5E5A-3AD3-E053-1464F80AA5D4',sysdate,'kfstem',0,'" + ADDrecord_guid + "','" + ADDstaff_id + "','" + DEFAULTROLEGROUP + "'," + KhbyID + ",'" + Checkguid + "' )";
                                data[1] = "insert into khn_assignhistory(REC_GUID,ASSIGNLIST_GUID,RECORD_GUID,KHTYPE,KHCONFIG_ID,KHCONFIGDATE_ID,KHGROUP,KHBY,KHTOBY,CREATEDATE,CREATEBY,source, CHECKGUID)select sysguid,ka.assignlist_guid,ka.relationid1,ka.khtype,ka.khconfig_id,ka.khconfigdate_id,ka.khgroup,ka.khby,ka.khtoby,sysdate,ka.RECORDBY,14, ka.CHECKGUID from khn_assignlist ka where ka.ASSIGNLIST_GUID ='" + ADDASSIGNLIST_GUID + "'";

                                int[] dataresult = eliteBean.updateBatch(data, "dataSource");

                                //轮循质检员完成后，重新轮循
                                if (j == KhbyArr.length - 1) {
                                    j = 0;
                                } else {
                                    j++;
                                }
                            }
                            // log.debug("加抽日志输出："+RECORDKHNLOG)
                        }

                    }
                }
                log.debug("加抽日志输出：" + RECORDKHNLOG)
            }
        }
    }

    /**
     * @use 录音自动抽检
     */
    private static ReCordKHNAssign(EliteBean eliteBean, List KHNAssignList) {

        for (def i = 0; i < KHNAssignList.size(); i++) {
            log.debug("执行抽检规则：" + KHNAssignList[i].get("CHECKGUID"));
            String Checkguid = KHNAssignList[i].get("CHECKGUID"); //抽检规则guid
            String Rolegroupid = KHNAssignList[i].get("Rolegroupid"); //抽取组
            String Staffid = KHNAssignList[i].get("Staffid"); //抽取人
            String Summarytmplidlist = KHNAssignList[i].get("Summarytmplidlist"); //小结模板
            String Businesstype1 = KHNAssignList[i].get("Businesstype1"); //小结业务类型1
            String Businesstype2 = KHNAssignList[i].get("Businesstype2"); //小结业务类型2
            String Businesstype3 = KHNAssignList[i].get("Businesstype3"); //小结业务类型3
            String Timetype = KHNAssignList[i].get("Timetype"); //时间段
            String Callstarttime = KHNAssignList[i].get("Callstarttime"); //通话时长开始
            String Callendtime = KHNAssignList[i].get("Callendtime"); //通话时长结束
            String Workstarttime = KHNAssignList[i].get("Workstarttime"); //入职开始时间
            String Workendtime = KHNAssignList[i].get("Workendtime"); //入职结束时间
            String Ratio = KHNAssignList[i].get("Ratio"); //抽取比例
            String Khby = KHNAssignList[i].get("Khby"); //质检员
            String Config_Id = KHNAssignList[i].get("Config_Id"); //质检计划
            String AutomaticGUID = UUID.randomUUID().toString(); //当前抽检批次GUID

            //质检计划、抽检比例、质检员不为空，执行方法
            if (!Config_Id.equals("") && !Ratio.equals("") && !Khby.equals("")) {

                String WhereCondition = ""; //SQL条件片段
                if (!KHUtil.isNull(Staffid)) { //抽取坐席
                    WhereCondition += " and r.staff_id in (" + Staffid + ") ";
                }
                if (!KHUtil.isNull(Rolegroupid)) { //抽取业务组
                    WhereCondition += " and st.title in (" + Rolegroupid + ") ";
                }
                if (!KHUtil.isNull(Summarytmplidlist)) { //小结模板
                    WhereCondition += " and ec.SUMMARYTMPLID in (" + Summarytmplidlist + ") ";
                }
                if (!KHUtil.isNull(Businesstype1)) { //业务1级
                    WhereCondition += " and ec.CALLNATUREGROUP_id in (" + Businesstype1 + ") ";
                }
                if (!KHUtil.isNull(Businesstype2)) { //业务2级
                    WhereCondition += " and ec.callnature_id in (" + Businesstype2 + ") ";
                }
                if (!KHUtil.isNull(Businesstype3)) { //业务3级
                    WhereCondition += " and ec.callnature3_id in (" + Businesstype3 + ") ";
                }
                if (!KHUtil.isNull(Timetype)) { //时间段
                    WhereCondition += " and dt.dateitem_id in (" + Timetype + ") ";
                }
                if (!KHUtil.isNull(Callstarttime)) { //通话时长开始时间段
                    WhereCondition += " and (r.endtime - r.starttime)*24*60*60 >= '" + Callstarttime + "' ";
                }
                if (!KHUtil.isNull(Callendtime)) { //通话时长时间段
                    WhereCondition += " and (r.endtime - r.starttime)*24*60*60 <= '" + Callendtime + "' ";
                }
                if (!KHUtil.isNull(Workstarttime)) { //入职开始时间
                    WhereCondition += " and trunc(months_between(sysdate,to_date(to_char(employeddate,'yyyymm'),'yyyymm')))> '" + Workstarttime + "' ";
                }
                if (!KHUtil.isNull(Workendtime)) { //入职结束时间
                    WhereCondition += " and trunc(months_between(sysdate,to_date(to_char(employeddate,'yyyymm'),'yyyymm')))< '" + Workendtime + "' ";
                }

                log.debug("【WhereCondition】：" + WhereCondition);



                //2024-09-11更新-取坐席列表
                 String AssignStaffSQL = '''select  r.staff_id,count(*) as staffcallcount
                                                    from record r 
                                                      left join KHN_ASSIGNLIST ka on r.RECORD_GUID=KA.RELATIONID1  
                                                      left join rolegroup rg on r.rolegroup_id=rg.rolegroup_id  
                                                      left join eventcallnature ec on ec.event_guid = r.event_guid
                                                      left join staff st on r.staff_id=st.staff_ID
                                                      left join WMSK_STATISFACTION wss on wss.event_guid=r.event_guid   
                                                    where 1=1 
                                                    and ka.assignlist_guid is null 
                                                    and nvl(wss.STATISFACTION1,0) >= 0  
                                                    and nvl(wss.STATISFACTION1,0) <= 2 
                                                    and st.Exemption = 0  
                                                    and trunc(r.starttime) = trunc(sysdate)-1 
                                                ''' + WhereCondition + "group by r.staff_id";

                List AssignStaffList = eliteBean.chaxun_sql(AssignStaffSQL, "dataSource");
                log.debug("每个坐席当日录音数量:" + AssignStaffList.toString());



                //取总数
                String AssignCountSQL = '''select distinct record_guid,r.rolegroup_id,r.staff_id
                                                    from record r 
                                                      left join KHN_ASSIGNLIST ka on r.RECORD_GUID=KA.RELATIONID1  
                                                      left join rolegroup rg on r.rolegroup_id=rg.rolegroup_id  
                                                      left join eventcallnature ec on ec.event_guid = r.event_guid
                                                      left join staff st on r.staff_id=st.staff_ID
                                                      left join WMSK_STATISFACTION wss on wss.event_guid=r.event_guid   
                                                    where 1=1 
                                                    and ka.assignlist_guid is null 
                                                    and nvl(wss.STATISFACTION1,0) >= 0  
                                                    and nvl(wss.STATISFACTION1,0) <= 2 
                                                    and st.Exemption = 0  
                                                    and trunc(r.starttime) = trunc(sysdate)-1 
                                                ''' + WhereCondition;
                log.debug("录音总数SQL:" + AssignCountSQL);
                List AssignCountList = eliteBean.chaxun_sql(AssignCountSQL, "dataSource");
                int RecordCount = AssignCountList.size();
                log.debug("录音常规抽检非比例总数:" + RecordCount);

                if (RecordCount > 0) {
                    //计算抽检数
                    int AssignCount = (int) ((RecordCount * (Ratio.toInteger() as Number)) / 100);
                    log.debug("录音常规抽检比例总数:" + AssignCount);




                    //处理质检员为List，并打乱List数据
                    String KhbyArrString = Khby.replace("\"", "");
                    String[] KhbyArr = KhbyArrString.split(",");
                    //KhbyList = Collections.shuffle(KhbyList); //随机打乱顺序
                    //初始化数据
                    int j = 0;
                    int s = 0;
                    int KhbyCount = 0;
                    String record_guid = "";
                    String staff_id = "";
                    String KhbyID = "";
                    String ASSIGNLIST_GUID = ""; //当前分配GUID
                    String DEFAULTROLEGROUP = "";
                    String WEHRESTAFF = "";
                    String[] data = new String[2];
                    //轮循分配,先轮循抽检数
                    for (int k = 0; k < AssignCount; k++) {
                        ASSIGNLIST_GUID = UUID.randomUUID().toString();
                        //2024-09-11更新
                        //取坐席录音，循环取，确保每个坐席都能取到

                        WEHRESTAFF = " and r.staff_id='"+AssignStaffList[s].get("staff_id")+"'"
                         String AssignStaffRecordSQL = '''select distinct record_guid,r.rolegroup_id,r.staff_id
                                                    from record r 
                                                      left join KHN_ASSIGNLIST ka on r.RECORD_GUID=KA.RELATIONID1  
                                                      left join rolegroup rg on r.rolegroup_id=rg.rolegroup_id  
                                                      left join eventcallnature ec on ec.event_guid = r.event_guid
                                                      left join staff st on r.staff_id=st.staff_ID
                                                      left join WMSK_STATISFACTION wss on wss.event_guid=r.event_guid   
                                                    where 1=1 
                                                    and ka.assignlist_guid is null 
                                                    and nvl(wss.STATISFACTION1,0) >= 0  
                                                    and nvl(wss.STATISFACTION1,0) <= 2 
                                                    and st.Exemption = 0 
                                                    and trunc(r.starttime) = trunc(sysdate)-1 
                                                ''' + WEHRESTAFF + WhereCondition;
                        List AssignStaffRecordList = eliteBean.chaxun_sql(AssignStaffRecordSQL, "dataSource");
                        //保护，如果取不到数据，跳出继续
                        if(AssignStaffRecordList.size()==0){
                            log.debug("坐席未查到录音数据:" + AssignStaffList[s].get("staff_id"));
                            continue;
                        }

                        //2025-01-05  --取消and rownum<=1，增加随机取法
                        int MinNumber = 0;
                        int MaxNumber = AssignStaffRecordList.size()-1;
                        int rangeRandomNumber = MinNumber + (int)(Math.random() * (MaxNumber + 1));

                        //取分配录音
                        record_guid = AssignStaffRecordList[rangeRandomNumber].get("record_guid"); //取需分配录音ID
                        staff_id = AssignStaffRecordList[rangeRandomNumber].get("staff_id"); //取录音坐席
                        //需循环到第几位质检员
                        KhbyID = KhbyArr[j];
                        List DEFAULTROLEGROUPLIST = eliteBean.chaxun_sql("select DEFAULTROLEGROUP from staff where STAFF_ID=" + KhbyID + "", "dataSource");
                        if (DEFAULTROLEGROUPLIST.size() > 0) {
                            DEFAULTROLEGROUP = DEFAULTROLEGROUPLIST.get(0).get("DEFAULTROLEGROUP");
                        }
                        //数据处理
                        data[0] = "insert into KHN_ASSIGNLIST(Automatic_guid,ASSIGNLIST_GUID,KHTYPE,KHCONFIG_ID,KHCONFIGDATE_ID,BUILDDATE,RECORDBY,KHFLAG,RELATIONID1,KHTOBY,KHGROUP,KHBY,CHECKGUID)values('" + AutomaticGUID + "','" + ASSIGNLIST_GUID + "','0','" + Config_Id + "','B2126F83-5E5A-3AD3-E053-1464F80AA5D4',sysdate,'kfstem',0,'" + record_guid + "','" + staff_id + "','" + DEFAULTROLEGROUP + "'," + KhbyID + ",'" + Checkguid + "' )";
                        data[1] = "insert into khn_assignhistory(REC_GUID,ASSIGNLIST_GUID,RECORD_GUID,KHTYPE,KHCONFIG_ID,KHCONFIGDATE_ID,KHGROUP,KHBY,KHTOBY,CREATEDATE,CREATEBY,source, CHECKGUID)select sysguid,ka.assignlist_guid,ka.relationid1,ka.khtype,ka.khconfig_id,ka.khconfigdate_id,ka.khgroup,ka.khby,ka.khtoby,sysdate,ka.RECORDBY,4, ka.CHECKGUID from khn_assignlist ka where ka.ASSIGNLIST_GUID ='" + ASSIGNLIST_GUID + "'";

                        eliteBean.updateBatch(data, "dataSource");

                        //轮循质检员完成后，重新轮循
                        if (j == KhbyArr.length - 1) {
                            j = 0;
                        } else {
                            j++;
                        }

                        //轮循坐席完成后，重新轮循
                        if (s == AssignStaffList.size() - 1) {
                            s = 0;
                        } else {
                            s++;
                        }
                    }
                }
            }
        }
    }

}